package initialize

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"rpc_demo/user_srv/global"
	"time"
)

func InitMysqlDb() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,        // Don't include params in the SQL log
			Colorful:                  true,        // Disable color
		},
	)

	user := global.ServiceConfig.MysqlConfig.User
	pwd := global.ServiceConfig.MysqlConfig.Password
	host := global.ServiceConfig.MysqlConfig.Host
	port := global.ServiceConfig.MysqlConfig.Port
	db := global.ServiceConfig.MysqlConfig.Name
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, pwd, host, port, db)

	var err error
	global.Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{TablePrefix: "pb_", SingularTable: true},
		Logger:         newLogger,
	})
	if err != nil {
		panic("failed to connect database")
	}
}
